package com.itdfq.loginuser.config;

import cn.hutool.json.JSONUtil;
import com.itdfq.loginuser.domain.DfqUsers;
import com.itdfq.loginuser.domain.Result;
import com.itdfq.loginuser.service.RedisService;
import com.itdfq.loginuser.service.UserService;
import com.itdfq.loginuser.utils.ThreadLocalUserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: QianMo
 * @Date: 2021/9/14 13:35
 * @Description:
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserService userService;

    private static final String LOGIN_TOKEN = "LOGIN-TOKEN";
    private static final List<String> EXCLUDE_URLS =
            Arrays.asList("/login","/test/decrypt","/test/encry","/lock/submit3");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(LOGIN_TOKEN);
        String url = request.getRequestURI();
        // 如果排除权限之外的链接地址
        if (EXCLUDE_URLS.contains(url)) {
            return true;
        }
        Integer userId = redisService.getToken(token);
        if (userId == null) {
            response.setContentType("application/json;charset=UTF-8");
            Result result = new Result();
            result.setSuccess(false).setCode(-1).setMsg("请登录");
            response.getWriter().println(JSONUtil.toJsonStr(result));
            return false;
        } else {
            DfqUsers byId = userService.findById(userId);
            log.info("当前登录用户信息:{}",JSONUtil.toJsonStr(byId));
            ThreadLocalUserUtils.set(byId);
            return true;
        }
    }


}
